/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entidade.controller.JSF;

import entidade.controller.JPA.EntradaSaidaJpaController;
import entidade.controller.JSF.util.PagingInfo;
import entidade.persistencia.EntradaSaida;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import javax.faces.FacesException;
import entidade.controller.JSF.util.JsfUtil;
import entidade.controller.JPA.exceptions.NonexistentEntityException;
import entidade.controller.JSF.util.DateComponentHelper;
import entidade.persistencia.Compra;
import entidade.persistencia.Venda;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;

/**
 *
 * @author victorinox
 */
public class EntradaSaidaController {

    public EntradaSaidaController() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        jpaController = (EntradaSaidaJpaController) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "entradaSaidaJpa");
        pagingInfo = new PagingInfo();
        converter = new EntradaSaidaConverter();
        dateFim.proximoMes();
    }
    private EntradaSaida entradaSaida = null;
    private List<EntradaSaida> entradaSaidaItems = null;
    private EntradaSaidaJpaController jpaController = null;
    private EntradaSaidaConverter converter = null;
    private PagingInfo pagingInfo = null;
    private DateComponentHelper dateInicio = new DateComponentHelper(new Date());
    private DateComponentHelper dateFim = new DateComponentHelper(new Date());
    private Float totalEntradaSaida = 0f;
    private Float totalVenda = 0f;
    private Float totalCompra = 0f;
    private Float totalManutencao = 0f;
    private Float totalFolha = 0f;
    private Boolean buscaVenda = true;
    private Boolean buscaCompra = true;
    private Boolean buscaManutencao = true;
    private Boolean buscaFolha = true;

    public PagingInfo getPagingInfo() {
        if (pagingInfo.getItemCount() == -1) {
            pagingInfo.setItemCount(jpaController.getEntradaSaidaCount());
            pagingInfo.setBatchSize(50);
        }
        return pagingInfo;
    }

    public SelectItem[] getEntradaSaidaItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(jpaController.findEntradaSaidaEntities(), false);
    }

    public SelectItem[] getEntradaSaidaItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(jpaController.findEntradaSaidaEntities(), true);
    }

    public EntradaSaida getEntradaSaida() {
        if (entradaSaida == null) {
            entradaSaida = (EntradaSaida) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentEntradaSaida", converter, null);
        }
        if (entradaSaida == null) {
            entradaSaida = new EntradaSaida();
        }
        return entradaSaida;
    }

    public String listSetup() {
        reset(true);
        return "entradaSaida_list";
    }

    public String createSetup() {
        reset(false);
        entradaSaida = new EntradaSaida();
        return "entradaSaida_create";
    }

    public String create() {
        try {
            jpaController.create(entradaSaida);
            JsfUtil.addSuccessMessage("EntradaSaida was successfully created.");
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return listSetup();
    }

    public String detailSetup() {
        return scalarSetup("entradaSaida_detail");
    }

    public String editSetup() {
        return scalarSetup("entradaSaida_edit");
    }

    private String scalarSetup(String destination) {
        reset(false);
        entradaSaida = (EntradaSaida) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentEntradaSaida", converter, null);
        if (entradaSaida == null) {
            String requestEntradaSaidaString = JsfUtil.getRequestParameter("jsfcrud.currentEntradaSaida");
            JsfUtil.addErrorMessage("The entradaSaida with id " + requestEntradaSaidaString + " no longer exists.");
            return relatedOrListOutcome();
        }
        return destination;
    }

    public String edit() {
        String entradaSaidaString = converter.getAsString(FacesContext.getCurrentInstance(), null, entradaSaida);
        String currentEntradaSaidaString = JsfUtil.getRequestParameter("jsfcrud.currentEntradaSaida");
        if (entradaSaidaString == null || entradaSaidaString.length() == 0 || !entradaSaidaString.equals(currentEntradaSaidaString)) {
            String outcome = editSetup();
            if ("entradaSaida_edit".equals(outcome)) {
                JsfUtil.addErrorMessage("Could not edit entradaSaida. Try again.");
            }
            return outcome;
        }
        try {
            jpaController.edit(entradaSaida);
            JsfUtil.addSuccessMessage("EntradaSaida was successfully updated.");
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return listSetup();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return detailSetup();
    }

    public String destroy() {
        String idAsString = JsfUtil.getRequestParameter("jsfcrud.currentEntradaSaida");
        Integer id = new Integer(idAsString);
        try {
            jpaController.destroy(id);
            JsfUtil.addSuccessMessage("EntradaSaida was successfully deleted.");
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return relatedOrListOutcome();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return relatedOrListOutcome();
    }

    private String relatedOrListOutcome() {
        String relatedControllerOutcome = relatedControllerOutcome();
        if (relatedControllerOutcome != null) {
            return relatedControllerOutcome;
        }
        return listSetup();
    }

    public List<EntradaSaida> getEntradaSaidaItems() {

        getPagingInfo();
        entradaSaidaItems = jpaController.findEntradaSaidaEntities(dateInicio.getDate(), dateFim.getDate());
        //entradaSaidaItems = jpaController.findEntradaSaidaEntities(pagingInfo.getBatchSize(), pagingInfo.getFirstItem());
        entradaSaidaItems = preencherEntradaSaidaItens(entradaSaidaItems);
        pagingInfo.setItemCount(entradaSaidaItems.size());
        pagingInfo.setBatchSize(entradaSaidaItems.size());
        return entradaSaidaItems;
    }

    private List<EntradaSaida> preencherEntradaSaidaItens(List<EntradaSaida> entradaSaidas) {
        if (entradaSaidas == null) {
            return new ArrayList<EntradaSaida>();
        }
        totalEntradaSaida = new Float(0.0);
        totalVenda = new Float(0.0);
        totalCompra = new Float(0.0);
        List<EntradaSaida> entradaSaidasReturn = new ArrayList<EntradaSaida>();
        for (int i = 0; i < entradaSaidas.size(); i++) {
            EntradaSaida entSaida = entradaSaidas.get(i);
            
            if (buscaVenda) {
                if (entSaida.getVendaCollection().size() > 0) {
                    Venda venda = entSaida.getVendaCollection().get(0);
                    if (venda.getObservacao() != null) {
                        entSaida.setResumoDinamico(venda.getClienteId().getEmpresaId().getNome());
                    }
                    entSaida.setTotalOperacao(venda.getTotalVenda());
                    totalVenda += entSaida.getValor();
                    entradaSaidasReturn.add(entSaida);
                }
            }
            if (buscaCompra) {
                if (entSaida.getCompraCollection().size() > 0) {
                    Compra compra = entSaida.getCompraCollection().get(0);
                    if (compra.getObservacao() != null) {
                        entSaida.setResumoDinamico(compra.getVendedorId().getEmpresaId().getNome());
                    }
                    entSaida.setTotalOperacao(compra.getTotalCompra() * -1);
                    totalCompra += entSaida.getValor();
                    entradaSaidasReturn.add(entSaida);
                }
            }
            totalEntradaSaida += entSaida.getValor();
        }
        return entradaSaidasReturn;
    }

    public Float getTotalEntradaSaida() {
        return totalEntradaSaida;
    }

    public String buscar() {

        return "entradaSaida_list";
    }

    public String next() {
        reset(false);
        getPagingInfo().nextPage();
        return "entradaSaida_list";
    }

    public String prev() {
        reset(false);
        getPagingInfo().previousPage();
        return "entradaSaida_list";
    }

    private String relatedControllerOutcome() {
        String relatedControllerString = JsfUtil.getRequestParameter("jsfcrud.relatedController");
        String relatedControllerTypeString = JsfUtil.getRequestParameter("jsfcrud.relatedControllerType");
        if (relatedControllerString != null && relatedControllerTypeString != null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Object relatedController = context.getApplication().getELResolver().getValue(context.getELContext(), null, relatedControllerString);
            try {
                Class<?> relatedControllerType = Class.forName(relatedControllerTypeString);
                Method detailSetupMethod = relatedControllerType.getMethod("detailSetup");
                return (String) detailSetupMethod.invoke(relatedController);
            } catch (ClassNotFoundException e) {
                throw new FacesException(e);
            } catch (NoSuchMethodException e) {
                throw new FacesException(e);
            } catch (IllegalAccessException e) {
                throw new FacesException(e);
            } catch (InvocationTargetException e) {
                throw new FacesException(e);
            }
        }
        return null;
    }

    private void reset(boolean resetFirstItem) {
        entradaSaida = null;
        entradaSaidaItems = null;
        pagingInfo.setItemCount(-1);
        if (resetFirstItem) {
            pagingInfo.setFirstItem(0);
        }
    }

    public void validateCreate(FacesContext facesContext, UIComponent component, Object value) {
        EntradaSaida newEntradaSaida = new EntradaSaida();
        String newEntradaSaidaString = converter.getAsString(FacesContext.getCurrentInstance(), null, newEntradaSaida);
        String entradaSaidaString = converter.getAsString(FacesContext.getCurrentInstance(), null, entradaSaida);
        if (!newEntradaSaidaString.equals(entradaSaidaString)) {
            createSetup();
        }
    }

    public Converter getConverter() {
        return converter;
    }

    /**
     * @return the dateInicio
     */
    public DateComponentHelper getDateInicio() {
        return dateInicio;
    }

    /**
     * @param dateInicio the dateInicio to set
     */
    public void setDateInicio(DateComponentHelper dateInicio) {
        this.dateInicio = dateInicio;
    }

    /**
     * @return the dateFim
     */
    public DateComponentHelper getDateFim() {
        return dateFim;
    }

    /**
     * @param dateFim the dateFim to set
     */
    public void setDateFim(DateComponentHelper dateFim) {
        this.dateFim = dateFim;
    }

    /**
     * @return the totalVenda
     */
    public Float getTotalVenda() {
        return totalVenda;
    }

    /**
     * @param totalVenda the totalVenda to set
     */
    public void setTotalVenda(Float totalVenda) {
        this.totalVenda = totalVenda;
    }

    /**
     * @return the totalCompra
     */
    public Float getTotalCompra() {
        return totalCompra;
    }

    /**
     * @param totalCompra the totalCompra to set
     */
    public void setTotalCompra(Float totalCompra) {
        this.totalCompra = totalCompra;
    }

    /**
     * @return the totalManutencao
     */
    public Float getTotalManutencao() {
        return totalManutencao;
    }

    /**
     * @param totalManutencao the totalManutencao to set
     */
    public void setTotalManutencao(Float totalManutencao) {
        this.totalManutencao = totalManutencao;
    }

    /**
     * @return the totalFolha
     */
    public Float getTotalFolha() {
        return totalFolha;
    }

    /**
     * @param totalFolha the totalFolha to set
     */
    public void setTotalFolha(Float totalFolha) {
        this.totalFolha = totalFolha;
    }

    /**
     * @return the buscaVenda
     */
    public Boolean getBuscaVenda() {
        return buscaVenda;
    }

    /**
     * @param buscaVenda the buscaVenda to set
     */
    public void setBuscaVenda(Boolean buscaVenda) {
        this.buscaVenda = buscaVenda;
    }

    /**
     * @return the buscaCompra
     */
    public Boolean getBuscaCompra() {
        return buscaCompra;
    }

    /**
     * @param buscaCompra the buscaCompra to set
     */
    public void setBuscaCompra(Boolean buscaCompra) {
        this.buscaCompra = buscaCompra;
    }

    /**
     * @return the buscaManutencao
     */
    public Boolean getBuscaManutencao() {
        return buscaManutencao;
    }

    /**
     * @param buscaManutencao the buscaManutencao to set
     */
    public void setBuscaManutencao(Boolean buscaManutencao) {
        this.buscaManutencao = buscaManutencao;
    }

    /**
     * @return the buscaFolha
     */
    public Boolean getBuscaFolha() {
        return buscaFolha;
    }

    /**
     * @param buscaFolha the buscaFolha to set
     */
    public void setBuscaFolha(Boolean buscaFolha) {
        this.buscaFolha = buscaFolha;
    }
}
